<template>
  <a-card>
    <a-form layout="horizontal" :form="searchForm" @submit="handleSearch" autocomplete="off">
      <a-row type="flex" justify="start" :gutter="15">
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-auto-complete :data-source="distributors" v-decorator="['distributor']" :placeholder="$t('distributor')" :filter-option="filterOption" :allowClear="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-auto-complete :data-source="suppliers" v-decorator="['supplier']" :placeholder="$t('supplier')" :filter-option="filterOption" :allowClear="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="14" :sm="24">
          <a-form-item>
            <a-space>
              <a-button htmlType="submit" type="primary" icon="search">{{ $t('search') }}</a-button>
              <a-button type="primary" icon="plus" @click="showForm(null)">{{ $t('add') }}
              </a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <a-table size="middle" :columns="columns" :data-source="data" :pagination="false" :row-key="record => record.distributor + record.supplier" :loading="loading">
      <div slot="action" slot-scope="text, record">
        <a-space>
          <a-button @click="showForm(record)">
            <a-icon type="edit"/>
            {{ $t("edit") }}
          </a-button>
        </a-space>
      </div>
      <a-icon slot="isonline" slot-scope="text" :type="text?'check-circle':'close-circle'" :style="text?'color:#52c41a;font-size: 18px;':'font-size: 18px;'"/>
      <a-icon slot="useCache" slot-scope="text" :type="text?'check-circle':'close-circle'" :style="text?'color:#52c41a;font-size: 18px;':'font-size: 18px;'"/>
      <template v-for="(item, index) in columns" :slot="item.slotName">
        <span :key="index">{{ $t(item.slotName) }}</span>
      </template>
    </a-table>

    <a-modal v-model="editVisible" :maskClosable="false" :title="editTitle" :confirm-loading="confirmLoading" :okText="$t('submit')" @ok="saveForm()" @cancel="closeForm()" width="60%">
      <a-form-model ref="updateForm" layout="vertical" :model="updateForm" autocomplete="off" :rules="updateFormRules">
        <a-row :gutter="[16,0]" justify="center">
          <a-col :span="12">
            <a-form-model-item prop="distributor" :label="$t('distributor')">
              <a-select :options="distributorSels" v-model="updateForm.distributor" :placeholder="$t('distributor')" :disabled="editReadonly">
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item prop="supplier" :label="$t('supplier')">
              <a-select :options="supplierSels" v-model="updateForm.supplier" :placeholder="$t('supplier')" :disabled="editReadonly">
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="5">
            <a-form-model-item prop="isonline" :label="$t('sale_status')">
              <a-switch v-model="updateForm.isonline">
              </a-switch>
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <a-form-model-item prop="useCache" :label="$t('use_cache')">
              <a-switch v-model="updateForm.useCache">
              </a-switch>
            </a-form-model-item>
          </a-col>
          <a-col :span="5">
            <a-form-model-item prop="min_adv_book_hour" :label="$t('min_adv_book_hour')">
              <a-input-number v-model="updateForm.minAdvBookHour" :min="2" :step="1" :precision="0"></a-input-number>
            </a-form-model-item>
          </a-col>
          <a-col :span="5">
            <a-form-model-item prop="min_stay_nights" :label="$t('min_stay_nights')">
              <a-input-number v-model="updateForm.minStayNights" :min="1" :step="1" :precision="0"></a-input-number>
            </a-form-model-item>
          </a-col>
          <a-col :span="5">
            <a-form-model-item prop="limit_nights" :label="$t('limit_nights')">
              <a-input-number v-model="updateForm.limitNights" :min="1" :precision="0"></a-input-number>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item prop="invalid_start_time" :label="$t('invalid_start_time')">
                <a-select v-model="updateForm.invalidStartTime" :options="hours" :placeholder="$t('start_time')" :allowClear="true">
                </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item prop="invalid_end_time" :label="$t('invalid_end_time')">
              <a-select v-model="updateForm.invalidEndTime" :options="hours" :placeholder="$t('end_time')" :allowClear="true">
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>

  </a-card>
</template>

<script>
import {getPublicData} from '@/services/public'
import {getSupplierSettingList,saveSupplierSetting} from '@/services/distributor'

export default {
  name: "SupplierSetting",
  i18n: require('../i18n'),
  data() {
    return {
      suppliers: [],
      supplierSels: [],
      distributors: [],
      distributorSels: [],
      hours: [{value: 0, label: '00'},
        {value: 1, label: '01'},
        {value: 2, label: '02'},
        {value: 3, label: '03'},
        {value: 4, label: '04'},
        {value: 5, label: '05'},
        {value: 6, label: '06'},
        {value: 7, label: '07'},
        {value: 8, label: '08'},
        {value: 9, label: '09'},
        {value: 10, label: '10'},
        {value: 11, label: '11'},
        {value: 12, label: '12'},
        {value: 13, label: '13'},
        {value: 14, label: '14'},
        {value: 15, label: '15'},
        {value: 16, label: '16'},
        {value: 17, label: '17'},
        {value: 18, label: '18'},
        {value: 19, label: '19'},
        {value: 20, label: '20'},
        {value: 21, label: '21'},
        {value: 22, label: '22'},
        {value: 23, label: '23'},
      ],
      searchParams: {},
      searchForm: this.$form.createForm(this, {name: 'search'}),
      loading: false,
      data: [],
      columns: [
        {
          dataIndex: 'distributor',
          align: 'center',
          slotName: "distributor",
          slots: { title: 'distributor' },
        },
        {
          dataIndex: 'supplier',
          align: 'center',
          slotName: "supplier",
          slots: { title: 'supplier' },
        },
        {
          dataIndex: 'isonline',
          align: 'center',
          slotName: "sale_status",
          slots: { title: 'sale_status' },
          scopedSlots: { customRender: 'isonline' },
        },
        {
          dataIndex: 'useCache',
          align: 'center',
          slotName: "use_cache",
          slots: { title: 'use_cache' },
          scopedSlots: { customRender: 'useCache' },
        },
        {
          dataIndex: 'minAdvBookHour',
          align: 'center',
          slotName: "min_adv_book_hour",
          slots: { title: 'min_adv_book_hour' },
        },
        {
          dataIndex: 'minStayNights',
          align: 'center',
          slotName: "min_stay_nights",
          slots: { title: 'min_stay_nights' },
        },
        {
          dataIndex: 'limitNights',
          align: 'center',
          slotName: "limit_nights",
          slots: { title: 'limit_nights' },
        },
        {
          dataIndex: 'invalidStartTime',
          align: 'center',
          slotName: "invalid_start_time",
          slots: { title: 'invalid_start_time' },
        },
        {
          dataIndex: 'invalidEndTime',
          align: 'center',
          slotName: "invalid_end_time",
          slots: { title: 'invalid_end_time' },
        },
        {
          dataIndex: 'updatedByName',
          align:'center',
          slotName: "updatedByName",
          slots: { title: 'updatedByName' },
        },{
          dataIndex: 'updatedTime',
          align:'center',
          slotName: "updatedTime",
          slots: { title: 'updatedTime' },
        },{
          align:'center',
          scopedSlots: { customRender: 'action' },
          slotName: "operation",
          slots: { title: 'operation' },
        }
      ],
      updateForm: {
        distributor:'',
        supplier:'',
        isonline: true,
        minAdvBookHour: 24,
        minStayNights: 1,
        invalidStartTime: null,
        invalidEndTime: null,
        limitNights: 90,
        useCache: false,
      },
      editVisible: false,
      editReadonly: false,
      editTitle: '',
      confirmLoading: false,
      updateFormRules: {
        supplier: [{required: true, trigger: 'blur',message:' '}],
        distributor: [{required: true, trigger: 'blur',message:' '}],
        minAdvBookHour: [{required: true, trigger: 'blur',message:' '}],
        minStayNights: [{required: true, trigger: 'blur',message:' '}],
        limitNights: [{required: true, trigger: 'blur',message:' '}],
      },
    }
  },
  methods: {
    getData() {
      getPublicData('sup_dis').then(res => {
        const {suppliers, distributors} = res.data
        this.suppliers = suppliers
        suppliers.forEach(item => {
          this.supplierSels.push({label: item, value: item})
        })
        this.distributors = distributors
        distributors.forEach(item => {
          this.distributorSels.push({label: item, value: item})
        })
      }).catch(error => {
        console.log(error)
      })
    },
    fetchData() {
      this.loading = true
      getSupplierSettingList(this.searchParams).then(res => {
        this.data = res.data.data
        this.loading = false
      }).catch(error => {
        console.log(error)
        this.loading = false
      })
    },
    handleSearch(e) {
      e.preventDefault();
      this.searchForm.validateFields((error, values) => {
        this.searchParams = values;
      });
      this.fetchData()
    },
    showForm(record) {
      if (record === null) {
        this.editTitle = this.$t('add')
        this.editReadonly = false
      } else {
        this.editTitle = this.$t('edit')
        this.updateForm = JSON.parse(JSON.stringify(record))
        this.editReadonly = true
      }
      this.editVisible = true
    },
    saveForm() {
      this.$refs.updateForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          saveSupplierSetting(this.updateForm).then(res => {
            if(res.data.success) {
              this.$message.success({content: this.$t('submitSuccess')})
              this.closeForm()
              this.fetchData()
            }else{
              this.$message.error({content: this.$t(res.data.message)})
            }
          }).catch(error => {
            console.log(error)
          })
        } else {
          return false;
        }
      });
    },
    closeForm() {
      this.confirmLoading = false
      this.editVisible = false
      this.updateForm = {
        distributor:'',
        supplier:'',
        isonline: true,
        minAdvBookHour: 24,
        minStayNights: 1,
        invalidStartTime: null,
        invalidEndTime: null,
        limitNights: 90,
        useCache: false,
      }
      this.$refs.updateForm.clearValidate()
    },
    filterOption(input, option) {
      return (
          option.componentOptions.children[0].text.toUpperCase().indexOf(input.toUpperCase()) >= 0
      );
    },
  },
  created() {
    this.getData();
    this.fetchData();
  },
}
</script>

<style scoped>

</style>